<?php

namespace Restaurant\Controller;


use Core\Constant;
use Core\Controller\RestaurantAdminBaseController;
use Core\Exception\BusinessException;
use Core\Helper\CommonHelper;
use Core\Helper\HtmlPurifierHelper;
use Core\Session\FrontSessionHelper;
use Exception;
use Zend\View\Model\JsonModel;

class GeneralDishController extends RestaurantAdminBaseController {
    public function indexAction() {
        $this->initPageWithLayout();

        $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
            FrontSessionHelper::getCurrentLang());
        $allDishCategories = array();
        $allGroupCode = $categoryTable->getAllGroupCode();
        foreach ($allGroupCode as $aGroupCode) {
            $tmpArr = $categoryTable->getAllCategoriesByGroupCode(
                $aGroupCode);

            $allDishCategories = array_merge($allDishCategories, $tmpArr);
        }

        $this->getViewModel()->setVariable('allDishCategories', $allDishCategories);

        return $this->getViewModel();
    }

    public function listAction()
    {
        try{
            $categoryId = $this->params()->fromPost("category");
            $name = $this->params()->fromPost("name");

            $searchOption = array();
            $searchOption['categoryId'] = $categoryId;

            $searchOption['name'] = $name;

            $sortData = $this->params()->fromPost("sort");
            if($sortData){
                $order = array();
                foreach ($sortData as $sortField) {
                    $field = $sortField['field'];
                    $direction = $sortField['dir'];
                    if($field == 'order_number'){
                        if($direction == 'asc')
                            $direction = 'desc';
                        else
                            $direction = 'asc';
                    }
                    $orderClause = $field." ".$direction;
                    array_push($order, $orderClause);
                }
            }else{
                $order = array("order_number desc");
            }

            $page = $this->params()->fromPost("page");
            $rows = $this->params()->fromPost("pageSize");
            $offset = ($page - 1) * $rows;

            $dishTable = $this->getResTableFinder()->
                getDishTable(FrontSessionHelper::getCurrentLang());
            $result = $dishTable->search(true, $offset, $rows, $order, $searchOption);

            return new JsonModel(array(
                'rows' => $result['rows'],
                'total' => $result['total'],
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function addAction() {
        $this->initPageWithLayout();
        $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
            FrontSessionHelper::getCurrentLang());
        $allMainDishGroup = $categoryTable->getAllCategoriesByGroupCode(
            Constant::$CATEGORY_GROUP_DISH);
        unset($allMainDishGroup[0]);
        $this->getViewModel()->setVariable('allMainDishGroup', $allMainDishGroup);

        $allSubDishGroup = array();
        $allGroupCode = $categoryTable->getAllGroupCode();
        foreach ($allGroupCode as $aGroupCode) {
             $tmpArr = $categoryTable->getAllCategoriesByGroupCode(
                $aGroupCode);

            $allSubDishGroup = array_merge($allSubDishGroup, $tmpArr);
        }


//        unset($allSubDishGroup[0]);
        $this->getViewModel()->setVariable('allSubDishGroup', $allSubDishGroup);

        $id =  $this->params()->fromQuery('id');
        $dishTable = $this->getResTableFinder()->getDishTable(
            FrontSessionHelper::getCurrentLang());
        $dishItem = $dishTable->getDish($id);
        $this->getViewModel()->setVariable('dishItem', $dishItem);

        $unitTable = $this->getResTableFinder()->getUnitTable(
            FrontSessionHelper::getCurrentLang());

        $allUnitAsArray = $unitTable->getAllAsArray();
        $this->getViewModel()->setVariable('allUnitAsArray', $allUnitAsArray);

        return $this->getViewModel();
    }


    public function saveAction(){
        try{
            $id = $this->params()->fromPost('id');
            $name = HtmlPurifierHelper::purifyDefault($this->params()->fromPost('name'));
            $description = HtmlPurifierHelper::purifyDefault($this->params()->fromPost('description'));
            $content = HtmlPurifierHelper::purifyDefault($this->params()->fromPost('content'));
            $howTo = HtmlPurifierHelper::purifyDefault($this->params()->fromPost('howTo'));
            $ingredient = HtmlPurifierHelper::purifyDefault($this->params()->fromPost('ingredient'));
            $allImages = $this->params()->fromPost('allImages');
            $categories = $this->params()->fromPost('categories');
            $subcategories = $this->params()->fromPost('subcategories');
            $active = $this->params()->fromPost('active');
            $priceArr = $this->params()->fromPost('priceArr');
            $properties = $this->params()->fromPost('properties');

            $this->validateSaveDish($id, $name, $priceArr);

            $dishTable = $this->getResTableFinder()->
                getDishTable(FrontSessionHelper::getCurrentLang());
            $transProxy = $this->getTableGatewayTransactionProxy();
            $transProxy->setAbstractTable($dishTable);

            if(!$id){
                $transProxy->addDish(array('name'=>$name,'description'=>$description,
                'content'=>$content,'howTo'=>$howTo,'ingredient'=>$ingredient,'allImages'=>$allImages,
                    'categories'=>$categories,'subcategories'=>$subcategories,'active'=>$active,
                    'priceArr'=>$priceArr,'properties'=>$properties,));
            }else{
                $transProxy->updateDish(array('name'=>$name,'description'=>$description,
                    'content'=>$content,'howTo'=>$howTo,'ingredient'=>$ingredient,'allImages'=>$allImages,
                    'categories'=>$categories,'subcategories'=>$subcategories,'active'=>$active,
                    'priceArr'=>$priceArr,'properties'=>$properties,), $id);
            }

            return new JsonModel(array('success'=>true));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    private function validateSaveDish($id, $name, $priceArr){
        $dishLangTable = $this->getResTableFinder()->
            getDishLangTable(FrontSessionHelper::getCurrentLang());
        $dishLang = $dishLangTable->getDishLangByAlias(CommonHelper::vietnameseToASCII($name));
        if(!$id){
            if($dishLang)
                throw new BusinessException('Đã tồn tại món ăn có tên: '.$name.'.');

        }else{
            if($dishLang && $dishLang->dish_id != $id)
                throw new BusinessException('Đã tồn tại món ăn có tên: '.$name.'.');
        }

        if(count($priceArr) < 1)
            throw new BusinessException('Bạn chưa nhập giá.');
        return true;
    }

    public function activeAction()
    {
        try{
           
            $id = $this->params()->fromPost('id');

            $dishTable = $this->getResTableFinder()->getDishTable(FrontSessionHelper::getCurrentLang());

            $dishTable->toggleActive($id);

            return new JsonModel(array(
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function doUpAction()
    {
        try{
            
            $id = $this->params()->fromPost('id');

            $dishTable = $this->getResTableFinder()->getDishTable(
                FrontSessionHelper::getCurrentLang());

            $dishTable->upDish($id);

            return new JsonModel(array(
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function doDownAction()
    {
        try{
            
            $id = $this->params()->fromPost('id');

            $dishTable = $this->getResTableFinder()->getDishTable(
                FrontSessionHelper::getCurrentLang());

            $dishTable->downDish($id);

            return new JsonModel(array(
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function deleteAction()
    {
        try{

            $id = $this->params()->fromQuery('id');

            $dishTable = $this->getResTableFinder()->
                getDishTable(FrontSessionHelper::getCurrentLang());

            $transactionProxy = $this->getTableGatewayTransactionProxy();
            $transactionProxy->setAbstractTable($dishTable);

            $transactionProxy->doDelete($id);

            return new JsonModel(array(
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

}